﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using System;
using TomNet.Core.Options;

namespace TomNet.AspNetCore
{
    public static class CorsServiceCollectionExtensions
    {
        /// <summary>
        /// 设置跨域策略
        /// </summary>
        public static IServiceCollection AddCross(this IServiceCollection services)
        {
            //IConfiguration configuration = services.GetConfiguration();
            //var _IotOptions = configuration.GetTomNetOptions();

            IConfiguration configuration = services.GetConfiguration();
            CrossOptions cross = new CrossOptions();
            configuration.Bind("TomNet:Cross", cross);

            
            if (cross != null)
            {
                if (cross.CrossType == Entity.CrossType.Any)
                {
                    services.AddCors(options =>
                    {
                        //浏览器会发起2次请求,使用OPTIONS发起预检请求，第二次才是api异步请求
                        options.AddPolicy(cross.PolicyName, policy =>
                        {
                            policy
                            .SetIsOriginAllowed(_ => true)
                            .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                        });
                    });
                }
                else if (cross.CrossType == Entity.CrossType.Custom)
                {
                    services.AddCors(options =>
                    {
                        //浏览器会发起2次请求,使用OPTIONS发起预检请求，第二次才是api异步请求
                        options.AddPolicy(cross.PolicyName, policy =>
                        {
                            policy
                            .WithOrigins(cross.Urls)
                            .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                        });
                    });
                }
            }
            return services;
        }
    }
}
